<template>
    <div class="madp-livecode">
        <backTitle v-if="!showHome" @goBack="goHome" :title="showCreateCode ? `${transPageType(pageType)}渠道活码` : isStatisticsCstDetailShow ? '客户详情' : '数据统计'" />
        <div v-show="showHome">
            <div>
                <el-form :inline="true" :model="searchForm" ref="searchForm" class="madp-livecode-search-form">
                    <el-form-item>
                        <el-input v-model.trim="searchForm.name" placeholder="请输入活码名称" maxlength="20"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="fetchCodeList">搜索</el-button>
                        <el-button plain @click="clearSearchForm">清空</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <div class="madp-livecode-handle">
                <el-button type="primary" @click="onEditLivecode()">新建活码</el-button>
                <!-- <el-button @click="onEditLivecode('batch')"
					>批量创建活码</el-button
                >-->
                <el-button @click="checkGroupMore">批量分组</el-button>
                <el-button @click="downloadCodeMore">批量下载</el-button>
            </div>
            <div class="madp-livecode-container">
                <div class="madp-livecode-container-left">
                    <div class="madp-livecode-container-left-add" @click="isInputShow = true">
                        <div class="group-name-add">
                            <i class="el-icon-circle-plus"></i>
                            添加分组
                        </div>
                        <div class="group-name-input" v-show="isInputShow">
                            <el-input
                                type="text"
                                placeholder="输入名称后回车"
                                v-model.trim="name"
                                maxlength="18"
                                show-word-limit
                                @input="name = name.replace(/\s+/, '')"
                                @keyup.enter.native="addGroup"
                                ref="groupName"
                            />
                        </div>
                    </div>
                    <div class="group-name-list">
                        <div
                            v-for="item in groupList"
                            :key="item.id"
                            class="group-name-list-item"
                            :class="{
                                actived: activedGroup === item.id,
                                selected: selectedGroup === item.id
                            }"
                            @mouseenter="activedGroup = item.id"
                            @mouseleave="activedGroup = ''"
                            @click="onSelectedGroup(item)"
                        >
                            <div class="group-name-list-item-name">
                                <img src="/img/folder.png" alt />
                                <div class="name-text">{{ item.name }}</div>
                            </div>
                            <div class="group-name-list-item-info">
                                {{ item.count || '0' }}
                                <div v-if="activedGroup === item.id && item.id !== 0" class="group-name-handle">
                                    <div class="group-name-handle-box">
                                        <div class="handle-common" @click="onEditGroup(item)">修改名称</div>
                                        <div
                                            class="handle-common"
                                            :class="{
                                                'del-disable': item.count && item.count > 0
                                            }"
                                            @click="onDelGroup(item)"
                                        >
                                            删除分组
                                        </div>
                                    </div>
                                    <i slot="reference" class="el-icon-more"></i>
                                </div>
                                <i class="not-active" v-else></i>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="madp-livecode-container-right">
                    <el-table
                        :header-cell-style="{
                            background: 'rgb(255, 191, 191)',
                            color: 'rgb(44,44,44)'
                        }"
                        :data="tableData"
                        row-key="id"
                        ref="multipleTable"
                        @selection-change="handleSelectionChange"
                        stripe
                    >
                        <el-table-column type="selection" width="55" :reserve-selection="true"> </el-table-column>
                        <el-table-column label="二维码" width="105">
                            <template slot-scope="scope">
                                <div class="table-check-img">
                                    <img
                                        :src="scope.row.qrcodeUrl + '?' + new Date().getTime()"
                                        alt
                                        v-if="scope.row.qrcodeUrl"
                                        @click="
                                            isLargeImgShow = true;
                                            largeImgUrl = scope.row.qrcodeUrl + '?' + new Date().getTime();
                                        "
                                        class="madp-cursor"
                                    />
                                    <div v-else>--</div>
                                </div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="name" align="center" label="名称" width="150" show-overflow-tooltip></el-table-column>
                        <el-table-column prop="count" align="center" label="扫描添加次数" width="120">
                            <template slot-scope="scope">
                                <div>{{ scope.row.count || 0 }}</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createTime" align="center" label="创建时间" width="100"></el-table-column>
                        <el-table-column prop="useEmployeeListList" align="center" label="使用成员" show-overflow-tooltip>
                            <template slot="header">
                                <div>
                                    使用成员
                                </div>
                            </template>
                            <template slot-scope="scope">
                                <div class="page-content" v-if="scope.row.useEmployeeListList && scope.row.useEmployeeListList.length > 0">
                                    {{ scope.row.useEmployeeListList | nameFilter }}
                                    <!-- <el-tag
                                        v-for="(item, index) in scope.row.useEmployeeListList"
                                        :key="index"
                                        :color="item.status === 1 ? theme : '#e6e6e6'"
                                        :style="item.status === 1 ? 'color: #ffffff' : 'color: #999999'"
                                        >{{ item.userEmployeeName }}</el-tag
                                    > -->
                                </div>
                                <div v-else>--</div>
                            </template>
                        </el-table-column>
                        <el-table-column prop="tags" align="center" label="标签" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <div class="page-content" v-if="scope.row.tags && scope.row.tags.length > 0">
                                    {{ scope.row.tags | nameFilter }}
                                    <!-- <el-tag v-for="(item, index) in scope.row.tags" :key="index">{{ item }}</el-tag> -->
                                </div>
                                <div v-else>--</div>
                            </template>
                        </el-table-column>
                        <el-table-column fixed="right" label="操作" align="center" width="240">
                            <template slot-scope="scope">
                                <el-button type="text" @click="toStatistics(scope.row)">数据统计</el-button>
                                <el-button type="text" @click="openDetail(scope.row)">详情</el-button>
                                <el-button type="text" @click="downloadCode(scope.row)">下载</el-button>
                                <el-dropdown trigger="click" @command="(e) => onHandleCommand(e, scope.row)">
                                    <el-button type="text">
                                        编辑
                                        <i class="el-icon-arrow-down"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item command="1">修改</el-dropdown-item>
                                        <el-dropdown-item command="2">复制</el-dropdown-item>
                                        <el-dropdown-item command="3">删除</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div>
                        <el-pagination
                            background
                            :current-page="page.currentPage"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :page-sizes="[10, 20, 30, 50, 100]"
                            :page-size="page.pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="page.total"
                            style="float: right"
                        ></el-pagination>
                    </div>
                </div>
            </div>
            <el-dialog
                title="修改分组名称"
                :visible.sync="editGroupVisible"
                @close="
                    editGroupVisible = false;
                    name = '';
                "
                width="600px"
                :close-on-click-modal="false"
            >
                <el-row class="madp-edit-group">
                    <el-col :span="4" align="right">分组名称:</el-col>
                    <el-col :span="16">
                        <el-input type="text" placeholder="输入分组名称" v-model.trim="name" maxlength="18" show-word-limit @input="name = name.replace(/\s+/, '')" />
                    </el-col>
                </el-row>
                <div slot="footer" class="dialog-footer">
                    <el-button
                        :loading="editGroupLoading"
                        @click="
                            editGroupVisible = false;
                            name = '';
                        "
                        >取消</el-button
                    >
                    <el-button type="primary" :loading="editGroupLoading" @click="onSubmitGroup">确定</el-button>
                </div>
            </el-dialog>
            <el-dialog title="批量分组" :visible.sync="groupChangeVisible" @close="groupChangeVisible = false" width="600px" :close-on-click-modal="false">
                <div class="madp-change-group">
                    <div class="madp-change-group-label">选择分组</div>
                    <el-popover placement="bottom" width="400" trigger="click" ref="codeGroup" @hide="isDialogInputShow = false">
                        <div class="madp-change-group-content">
                            <div class="madp-change-group-content-add" @click="isDialogInputShow = true">
                                <div class="group-name-add">
                                    <i class="el-icon-circle-plus"></i>
                                    添加分组
                                </div>
                                <div class="group-name-input" v-show="isDialogInputShow">
                                    <el-input
                                        type="text"
                                        placeholder="输入名称后回车"
                                        v-model.trim="name"
                                        maxlength="18"
                                        show-word-limit
                                        @input="name = name.replace(/\s+/, '')"
                                        @keyup.enter.native="addGroup"
                                    />
                                </div>
                            </div>
                            <div class="group-name-list">
                                <div
                                    v-for="item in groupList.filter((group) => group.id !== 0)"
                                    :key="item.id"
                                    class="group-name-list-item"
                                    :class="{
                                        actived: activedGroup === item.id
                                    }"
                                    @mouseenter="activedGroup = item.id"
                                    @mouseleave="activedGroup = ''"
                                    @click="onSelectedChangeGroup(item)"
                                >
                                    <div class="group-name-list-item-name">{{ item.name }}</div>
                                    <div class="group-name-list-item-info">{{ item.count || '0' }}</div>
                                </div>
                            </div>
                        </div>
                        <el-input v-model="willChangeGroupName" placeholder="请选择分组" slot="reference" readonly>
                            <div class="madp-change-group-suffix" slot="suffix" @mouseenter="iconType = 'close'" @mouseleave="iconType = 'arrow'">
                                <i class="el-icon-arrow-down" v-if="iconType === 'arrow' || !willChangeGroupName"></i>
                                <i
                                    class="el-icon-error"
                                    v-if="iconType === 'close' && willChangeGroupName"
                                    @click.stop="
                                        willChangeGroupName = '';
                                        willChangeGroupId = '';
                                    "
                                ></i>
                            </div>
                        </el-input>
                    </el-popover>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button
                        :loading="groupChangeLoading"
                        @click="
                            groupChangeVisible = false;
                            willChangeGroupId = '';
                            willChangeGroupName = '';
                            name = '';
                        "
                        >取消</el-button
                    >
                    <el-button type="primary" :loading="groupChangeLoading" @click="onSubmitChangeGroup">确定</el-button>
                </div>
            </el-dialog>
            <el-dialog title="活码详情" :visible.sync="codeDtailVisible" @close="codeDtailVisible = false" width="800px" top="10vh" :close-on-click-modal="false">
                <div class="madp-code-detail">
                    <div class="madp-code-detail-left">
                        <img
                            :src="codeDetail.qrcodeUrl + '?' + new Date().getTime()"
                            alt
                            @click="
                                isLargeImgShow = true;
                                largeImgUrl = codeDetail.qrcodeUrl + '?' + new Date().getTime();
                            "
                            class="madp-cursor"
                        />
                        <div class="madp-code-detail-left-name">{{ codeDetail.name }}</div>
                        <div class="madp-code-detail-left-btn">
                            <el-button type="primary" @click="downloadCode(codeDetail)">下载活码</el-button>
                            <el-button @click="openDetail(codeDetail, 'edit')">修改</el-button>
                        </div>
                    </div>
                    <div class="madp-code-detail-right">
                        <el-scrollbar>
                            <div class="madp-code-detail-right-basic">
                                <div class="madp-common-title">基本设置</div>
                                <div class="madp-common-item">
                                    <div class="madp-common-item-left">创建时间:</div>
                                    <div class="madp-common-item-right">{{ codeDetail.createTime }}</div>
                                </div>
                                <div class="madp-common-item">
                                    <div class="madp-common-item-left">上线成员:</div>
                                    <div class="madp-common-item-right" v-if="codeDetail.onLineEmployList && codeDetail.onLineEmployList.length > 0">
                                        <el-tag v-for="item in codeDetail.onLineEmployList" :key="item.employeeId">{{ item.employeeName }}</el-tag>
                                    </div>
                                    <div class="madp-common-item-right" v-else>—</div>
                                </div>
                                <div class="madp-staff-limit" v-if="codeDetail.employeeAddUpperLimitStatus === 1">
                                    <el-table
                                        :header-cell-style="{
                                            background: 'rgb(255, 191, 191)',
                                            color: 'rgb(44,44,44)'
                                        }"
                                        :stripe="true"
                                        :data="codeDetail.employeeAddUpperLimitList"
                                    >
                                        <el-table-column :label="`共${codeDetail.employeeAddUpperLimitList.length}个员工`" align="center">
                                            <template slot-scope="scope">
                                                <div>{{ scope.row.employeeName }}</div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="今日添加客户数" prop="contactNum" align="center">
                                            <template slot-scope="scope">
                                                <div>
                                                    {{ scope.row.contactNum || 0 }}
                                                </div>
                                            </template>
                                        </el-table-column>
                                        <el-table-column label="每日添加客户上限" prop="maxNum" align="center"></el-table-column>
                                    </el-table>
                                </div>
                                <div class="madp-common-item">
                                    <div class="madp-common-item-left">自动通过好友:</div>
                                    <div class="madp-common-item-right">
                                        {{
                                            codeDetail.autoAddFriendStatus === 2
                                                ? '已关闭'
                                                : codeDetail.autoAddFriendTimeStatus === 1
                                                ? '全天开启'
                                                : `${codeDetail.autoAddFriendMsg && codeDetail.autoAddFriendMsg.autoAddFriendStartTime}-${codeDetail.autoAddFriendMsg &&
                                                      codeDetail.autoAddFriendMsg.autoAddFriendEndTime} 自动开启`
                                        }}
                                    </div>
                                </div>
                                <div class="madp-common-item">
                                    <div class="madp-common-item-left">客户标签:</div>
                                    <div class="madp-common-item-right" v-if="codeDetail.customerTagStatus === 2">已关闭</div>
                                    <div class="madp-common-item-right" v-else-if="codeDetail.customerTagStatus && codeDetail.customerTagList && codeDetail.customerTagList.length > 0">
                                        <el-tag v-for="item in codeDetail.customerTagList" :key="item.wxContactTagId">{{ item.name }}</el-tag>
                                    </div>
                                    <div class="madp-common-item-right" v-else>—</div>
                                </div>
                                <div class="madp-common-title madp-mt">欢迎语设置</div>
                                <div class="madp-wel-title">渠道码欢迎语:</div>
                                <div class="madp-wel-content">
                                    <div class="madp-wel-content-message">
                                        <span>欢迎语:</span>
                                        <span class="madp-wel-content-message-all" v-if="codeDetail.greetingStatus === 1" @click="onPreviewShow(codeDetail.channelGreetingMsg)">查看全部</span>
                                        <span v-if="codeDetail.greetingStatus === 2">默认欢迎语</span>
                                        <span v-if="codeDetail.greetingStatus === 3">不回复欢迎语</span>
                                    </div>
                                </div>
                                <div class="madp-wel-title" v-if="codeDetail.daypartingGreetingList && codeDetail.daypartingGreetingList.length > 0">分时段欢迎语:</div>
                                <div class="madp-wel-content" v-for="(item, index) in codeDetail.daypartingGreetingList" :key="index">
                                    <div class="madp-wel-content-time">
                                        <div class="madp-wel-content-time-left">时段{{ index + 1 }}:</div>
                                        <div class="madp-wel-content-time-right">
                                            <el-tag v-for="tag in item.weekList" :key="tag">
                                                {{ tag | transWeekDay }}
                                            </el-tag>
                                            <div>
                                                {{ item.daypartingGreetingStartTime }}
                                                -
                                                {{ item.daypartingGreetingEndTime }}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="madp-wel-content-message">
                                        <span>欢迎语:</span>
                                        <span class="madp-wel-content-message-all" @click="onPreviewShow(item)">查看全部</span>
                                    </div>
                                </div>
                            </div>
                        </el-scrollbar>
                    </div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="codeDtailVisible = false">确定</el-button>
                </div>
            </el-dialog>
            <div class="madp-wel-preview" v-if="isWelContentShow">
                <div class="madp-wel-preview-box">
                    <img class="madp-wel-preview-box-outre" src="/img/wel_preview.png" alt />
                    <div class="madp-wel-preview-box-inner">
                        <div class="madp-message" v-if="welContentInfo.words">
                            <div class="madp-message-left">
                                <i class="el-icon-user-solid"></i>
                            </div>
                            <div class="madp-message-right madp-message-common madp-message-common-box">{{ welContentInfo.words }}</div>
                        </div>
                        <div
                            class="madp-message"
                            v-for="(item, index) in welContentInfo.medium"
                            :key="index"
                            :class="{
                                'madp-mt': index !== 0 || welContentInfo.words
                            }"
                        >
                            <div class="madp-message-left">
                                <i class="el-icon-user-solid"></i>
                            </div>
                            <div class="madp-message-pic madp-message-common" v-if="item.type === 2">
                                <img :src="item.url" alt />
                            </div>
                            <div class="madp-message-picTxt madp-message-common madp-message-common-box" v-if="item.type === 3">
                                <img :src="item.content.imgUrl" alt />
                                <div class="madp-message-picTxt-info">
                                    <div class="madp-message-picTxt-info-top">{{ item.content.title }}</div>
                                    <div class="madp-message-picTxt-info-bottom">{{ item.content.description }}</div>
                                </div>
                            </div>
                            <div class="madp-message-applets madp-message-common madp-message-common-box" v-if="item.type === 6">
                                <div class="madp-message-applets-title">
                                    <img src="/img/applets.png" alt />
                                    <span>{{ item.content.title }}</span>
                                </div>
                                <img :src="item.content.imgUrl" alt />
                            </div>
                        </div>
                    </div>
                    <i class="el-icon-circle-close madp-wel-preview-box-close" @click="onPreviewClose"></i>
                </div>
            </div>
        </div>
        <div class="madp-livecode-component" v-show="showStatistics || showCreateCode">
            <statistics-block
                v-if="showStatistics"
                :channelCodeId="currentChannelCodeId"
                :channelCodeName="currentChannelCodeName"
                :isStatisticsCstDetailShow="isStatisticsCstDetailShow"
                @changeDetailShow="changeStatisticsDetailShow"
            ></statistics-block>
            <create-code v-if="showCreateCode" @goBack="goHome" :channelCodeId="currentChannelCodeId" :detailInfo="codeDetail" :pageType="pageType"></create-code>
        </div>
        <large-img
            :visible="isLargeImgShow"
            :imgUrl="largeImgUrl"
            @close="
                isLargeImgShow = false;
                imgUrl = '';
            "
        />
    </div>
</template>

<script>
import {
    queryCodeGroupList,
    addCodeGroup,
    editCodeGroup,
    delCodeGroup,
    queryChannelCode,
    queryChannelCodeDetail,
    delChannelCode,
    changeCodeGroup,
    downloadBatchCode
} from '@/api/customers-of-drainage/customers-of-drainage';
import StatisticsBlock from './statistics.vue';
import CreateCode from './create-code.vue';
import backTitle from '@/components/back-title/';
import LargeImg from '@/components/large-img';
import { mapGetters } from 'vuex';
export default {
    components: {
        StatisticsBlock,
        CreateCode,
        backTitle,
        LargeImg
    },
    props: ['oldSelectedGroup'],
    data() {
        return {
            // 默认显示主页
            showHome: true,
            // 显示数据统计界面
            showStatistics: false,
            currentChannelCodeId: '',
            // 显示新建活码界面
            showCreateCode: false,

            // 主页相关
            searchForm: {
                // 查询表单数据
                name: ''
            },
            groupList: [], // 分组数据
            isInputShow: false, // 新建分组输入框显隐
            name: '', // 分组名称
            activedGroup: '', // 滑入的分组ID
            selectedGroup: 0, // 选中的分组ID
            tableData: [],
            selectedType: undefined, // 活码表头下拉选选中
            selectedKeys: [], // 表格选中
            editGroupVisible: false, // 修改分组名称弹框显隐
            editGroupId: '', // 待修改的分组的groupId
            editGroupLoading: false, // 提交分组信息时的加载状态
            codeDtailVisible: false,
            codeDetail: {},
            isWelContentShow: false,
            // 表单数据
            welContentInfo: {},
            // 分页
            page: {
                total: 0,
                currentPage: 1,
                pageSize: 10
            },
            // 显示大图开关
            isLargeImgShow: false,
            // 大图路径
            largeImgUrl: '',
            // 修改分组弹窗开关
            groupChangeVisible: false,
            // 显示输入框
            isDialogInputShow: false,
            willChangeGroupId: '',
            willChangeGroupName: '',
            iconType: 'arrow',
            groupChangeLoading: false,
            isStatisticsCstDetailShow: false
        };
    },
    computed: {
        ...mapGetters(['theme'])
    },
    filters: {
        transWeekDay(value) {
            switch (value) {
                case 1:
                    return '周一';
                case 2:
                    return '周二';
                case 3:
                    return '周三';
                case 4:
                    return '周四';
                case 5:
                    return '周五';
                case 6:
                    return '周六';
                case 7:
                    return '周日';
                default:
                    break;
            }
        },
        transPageType(val) {
            switch (val) {
                case 'edit':
                    return '修改';
                case 'copy':
                    return '复制';
                case 'batch':
                    return '批量创建';
                default:
                    return '新建';
            }
        },
        nameFilter(val) {
            let arr = [];
            if (val[0] && val[0].userEmployeeName) {
                val.map((i) => {
                    arr.push(i.userEmployeeName);
                });
            } else {
                arr = val;
            }
            return arr.join('、');
        }
    },
    mounted() {
        this.selectedGroup = this.oldSelectedGroup;
        this.getGroupList();
        this.listenClick();
        this.getChannelCodeList();
    },
    methods: {
        // 修改选中内容
        handleSelectionChange(val) {
            this.selectedKeys = val;
        },
        // 页面类型
        transPageType(val) {
            switch (val) {
                case 'edit':
                    return '修改';
                case 'copy':
                    return '复制';
                case 'batch':
                    return '批量创建';
                default:
                    return '新建';
            }
        },
        // 隐藏统计或者新建活码界面，显示主界面
        goHome(isReload) {
            if (this.isStatisticsCstDetailShow) {
                this.isStatisticsCstDetailShow = false;
                return;
            }
            this.showStatistics = false;
            this.showCreateCode = false;
            this.currentChannelCodeId = '';
            this.pageType = '';
            this.showHome = true;
            this.codeDetail = {};
            this.$emit('changeTabShow', true);
            if (isReload) {
                this.getChannelCodeList();
                this.getGroupList();
            }
        },
        // 监听点击事件
        listenClick() {
            document.addEventListener('click', this.closeInput, true);
        },
        // 若点击元素非添加分组元素则不显示分组输入框
        closeInput(e) {
            if (this.isInputShow && e.path && !e.path.toString().includes('licecode-container-left-add')) {
                this.isInputShow = false;
            } else {
                this.$nextTick(() => {
                    this.$refs.groupName && this.$refs.groupName.focus();
                });
            }
        },
        // 查询渠道活码列表
        getChannelCodeList() {
            const params = {
                current: this.page.currentPage,
                size: this.page.pageSize,
                groupId: this.selectedGroup ? this.selectedGroup : undefined,
                name: this.searchForm.name ? this.searchForm.name : undefined
            };
            queryChannelCode(params).then((res) => {
                const newData = res.data.data.records || [];
                if (res.data.code === 0) {
                    this.tableData = res.data.data.records || [];
                    this.page.total = res.data.data.total || 0;
                    if (this.page.total > 0 && this.tableData.length == 0) {
                        this.page.currentPage = Math.max(1, this.page.currentPage - 1);
                        this.getChannelCodeList();
                    }
                    if (this.page.total === 0) {
                        this.$emit('changeSecondShow', {
                            isSecondShow: false,
                            id: this.selectedGroup
                        });
                    } else {
                        this.$emit('changeSecondShow', {
                            isSecondShow: true,
                            id: this.selectedGroup
                        });
                    }
                }
            });
        },
        // 新建渠道活码
        onEditLivecode(type) {
            this.showHome = false;
            this.showCreateCode = true;
            this.pageType = type;
            this.$emit('changeTabShow', false);
        },
        // 获取分组数据
        getGroupList() {
            queryCodeGroupList().then((res) => {
                if (res.data.code === 0) {
                    this.groupList = res.data.data || [];
                }
            });
        },
        // 选中分组
        onSelectedGroup(records) {
            if (this.selectedGroup == records.id) return;
            this.selectedGroup = records.id;
            this.page.currentPage = 1;
            this.$refs.multipleTable.clearSelection();
            this.getChannelCodeList();
        },
        // 选中将要批量的分组
        onSelectedChangeGroup(records) {
            this.willChangeGroupName = records.name;
            this.willChangeGroupId = records.id;
            if (this.$refs.codeGroup) {
                this.$refs.codeGroup.doClose();
            }
        },
        // 新建分组
        addGroup(e) {
            if (!e.target.value) return;
            const params = {
                nameList: [e.target.value]
            };
            addCodeGroup(params).then((res) => {
                if (res.data.code === 0) {
                    this.$message.success('新增分组成功');
                    this.isInputShow = false;
                    this.isDialogInputShow = false;
                    this.name = '';
                    this.getGroupList();
                }
            });
        },
        // 修改分组
        onEditGroup(records) {
            this.editGroupId = records.id;
            this.name = records.name;
            this.editGroupVisible = true;
        },
        // 提交分组修改信息
        onSubmitGroup() {
            this.editGroupLoading = true;
            const params = {
                groupId: this.editGroupId,
                name: this.name
            };
            editCodeGroup(params)
                .then((res) => {
                    if (res.data.code === 0) {
                        this.$message.success('修改分组成功');
                        this.editGroupId = '';
                        this.name = '';

                        this.editGroupVisible = false;
                        this.getGroupList();
                    }
                    this.editGroupLoading = false;
                })
                .catch(() => {
                    this.editGroupLoading = false;
                });
        },
        // 删除分组
        onDelGroup(records) {
            if (records.count && records.count > 0) return;
            this.$confirm('是否确认删除该分组？', '提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            })
                .then(() => {
                    delCodeGroup({ id: records.id }).then((res) => {
                        if (res.data.code === 0) {
                            this.$message.success('删除成功');
                            this.getGroupList();
                        }
                    });
                })
                .catch(() => {});
        },
        // 批量分组
        checkGroupMore() {
            if (!this.selectedKeys || this.selectedKeys.length === 0) {
                this.$message.error('请先勾选渠道活码');
            } else {
                this.groupChangeVisible = true;
            }
        },
        // 批量分组确认
        onSubmitChangeGroup() {
            if (this.willChangeGroupId) {
                this.groupChangeLoading = true;
                let arr = [];
                this.selectedKeys.map((i) => {
                    arr.push(i.id);
                });
                let params = {
                    codeIdList: arr
                };
                if (this.selectedType === 1) {
                    params = { type: 1 };
                }
                (params.groupId = this.willChangeGroupId),
                    changeCodeGroup(params)
                        .then((res) => {
                            this.groupChangeLoading = false;
                            if (res.data.code === 0) {
                                this.$message.success('批量分组成功');
                                this.$refs.multipleTable.clearSelection();
                                this.getGroupList();
                                this.getChannelCodeList();

                                this.groupChangeVisible = false;
                                this.willChangeGroupId = '';
                                this.willChangeGroupName = '';
                                this.selectedType = undefined;
                            }
                        })
                        .catch(() => {
                            this.groupChangeLoading = false;
                        });
            } else {
                this.$message.error('请选择分组');
            }
        },
        // 打开详情弹框
        openDetail(codeDetail, type) {
            this.codeDtailVisible = false;
            queryChannelCodeDetail(codeDetail.id).then((res) => {
                if (res.data.code === 0) {
                    const newDetail = JSON.parse(JSON.stringify(res.data.data));
                    if (!type) {
                        if (newDetail.customerServicePersonnelStatus === 1) {
                            newDetail.onLineEmployList = newDetail.employeeAllDayLongList;
                        } else {
                            const allStaffList = [];
                            newDetail.offLineEmployList = [];
                            newDetail.employeeTopBottomLineListByDetails.forEach((item) => {
                                allStaffList.push(...JSON.parse(JSON.stringify(item.employeeIdList)));
                            });
                            newDetail.onLineEmployList = allStaffList.filter((item) => item.status === 1);
                            const allOnLineStaffIds = newDetail.onLineEmployList.map((item) => item.employeeId);
                            const allOffLineStaffIds = [];
                            allStaffList.forEach((item) => {
                                if (!allOnLineStaffIds.includes(item.employeeId) && !allOffLineStaffIds.includes(item.employeeId)) {
                                    newDetail.offLineEmployList.push(item);
                                    allOffLineStaffIds.push(item.employeeId);
                                }
                            });
                        }
                        const allSelectedTag = [];
                        newDetail.customerTagList &&
                            newDetail.customerTagList.forEach((item) => {
                                allSelectedTag.push(...JSON.parse(JSON.stringify(item.tagNameList)));
                            });
                        newDetail.customerTagList = allSelectedTag;
                        this.codeDetail = newDetail;
                        this.codeDtailVisible = true;
                    } else {
                        // 图片赋值
                        delete newDetail.qrcodeUrl;
                        // 分组选中回显获取组名
                        const groupInfo = this.groupList.filter((item) => item.id === newDetail.groupId)[0];
                        if (groupInfo) {
                            newDetail.codeGroupName = groupInfo.name;
                        }
                        // 空字符串改为空数组
                        newDetail.employeeAllDayLongList = newDetail.employeeAllDayLongList || [];
                        newDetail.standbyEmployeeList = newDetail.standbyEmployeeList || [];
                        newDetail.greetingShieldList = newDetail.greetingShieldList || [];
                        newDetail.employeeAddUpperLimitList = newDetail.employeeAddUpperLimitList || [];
                        newDetail.employeeTopBottomLineList = newDetail.employeeTopBottomLineListByDetails || [];
                        // 时间为空字符串时初始化
                        newDetail.autoAddFriendMsg = newDetail.autoAddFriendMsg || {
                            autoAddFriendEndTime: null,
                            autoAddFriendStartTime: null
                        };
                        // 标签回显处理
                        const allSelectedTag = [];
                        newDetail.customerTagList &&
                            newDetail.customerTagList.forEach((item) => {
                                item.tagNameList.forEach((it) => {
                                    allSelectedTag.push({
                                        id: it.tagId,
                                        name: it.name
                                    });
                                });
                            });
                        newDetail.customerTagList = allSelectedTag;
                        // 欢迎语无值时初始化
                        newDetail.channelGreetingMsg = newDetail.channelGreetingMsg
                            ? (newDetail.channelGreetingMsg = {
                                  words: newDetail.channelGreetingMsg.words,
                                  annexList: newDetail.channelGreetingMsg.medium[0]
                                      ? {
                                            ...newDetail.channelGreetingMsg.medium[0].content,
                                            type: newDetail.channelGreetingMsg.medium[0].type,
                                            mediumId: newDetail.channelGreetingMsg.mediumId
                                        }
                                      : {}
                              })
                            : { words: '', annexList: {} };
                        // 分时段欢迎语无值时初始化
                        newDetail.daypartingGreetingList = newDetail.daypartingGreetingList
                            ? newDetail.daypartingGreetingList.map((item) => ({
                                  weekList: item.weekList,
                                  words: item.words,
                                  daypartingGreetingStartTime: item.daypartingGreetingStartTime,
                                  daypartingGreetingEndTime: item.daypartingGreetingEndTime,
                                  annexList: item.medium[0]
                                      ? {
                                            ...item.medium[0].content,
                                            type: item.medium[0].type,
                                            mediumId: item.mediumId
                                        }
                                      : {}
                              }))
                            : [];
                        this.codeDetail = newDetail;
                        this.pageType = type;
                        this.showHome = false;
                        this.showCreateCode = true;
                        this.$emit('changeTabShow', false);
                    }
                }
            });
        },
        // 下载活码
        downloadCode(urlInfo) {
            let a = document.createElement('a'); // 创建一个a节点插入的document
            let event = new MouseEvent('click'); // 模拟鼠标click点击事件
            a.download = urlInfo.name;
            a.href = urlInfo.qrcodeUrl + '?' + new Date().getTime(); // 将图片的src赋值给a节点的href
            a.dispatchEvent(event);
        },
        // 批量下载活码
        downloadCodeMore() {
            if (!this.selectedKeys || this.selectedKeys.length === 0) {
                this.$message.error('请先勾选渠道活码');
            } else {
                let arr = [];
                this.selectedKeys.map((i) => {
                    arr.push(i.id);
                });
                let params = {
                    channelId: arr
                };
                if (this.selectedType === 1) {
                    params = { type: 1 };
                }
                downloadBatchCode(params).then((res) => {
                    let blob = new Blob([res.data], {
                        type: 'application/zip' + ';charset=utf-8'
                    });
                    let src = window.URL.createObjectURL(blob);
                    if (src) {
                        let a = document.createElement('a');
                        a.setAttribute('href', src);
                        a.setAttribute('download', 'qrCode');
                        let evObj = document.createEvent('MouseEvents');
                        evObj.initMouseEvent('click', true, true, window, 0, 0, 0, 0, 0, false, false, true, false, 0, null);
                        a.dispatchEvent(evObj);
                    }
                    if (res.data.code === 0) {
                        this.$message.success('批量下载成功');
                    }
                });
            }
        },
        onHandleCommand(command, records) {
            switch (command) {
                case '1':
                    this.openDetail(records, 'edit');
                    break;
                case '2':
                    this.openDetail(records, 'copy');
                    break;
                case '3':
                    this.$confirm('是否确认删除该活码？', '提示', {
                        confirmButtonText: '确认',
                        cancelButtonText: '取消',
                        type: 'warning'
                    })
                        .then(() => {
                            delChannelCode({ id: records.id }).then((res) => {
                                if (res.data.code === 0) {
                                    this.$message.success('删除成功');
                                    this.getChannelCodeList();
                                    this.getGroupList();
                                }
                            });
                        })
                        .catch(() => {});
                    break;
                default:
                    break;
            }
        },
        fetchCodeList() {
            this.$nextTick(() => {
                this.page.currentPage = 1;
                this.getChannelCodeList();
            });
        },
        clearSearchForm() {
            this.searchForm.name = '';
            this.page = {
                currentPage: 1,
                pageSize: 10,
                total: 0
            };
            this.selectedType = '';
            this.$nextTick(() => {
                this.getChannelCodeList();
            });
        },
        toStatistics(data) {
            this.currentChannelCodeId = data.id;
            this.currentChannelCodeName = data.name;
            this.showHome = false;
            this.showStatistics = true;
            this.$emit('changeTabShow', false);
        },
        onPreviewShow(welContentInfo) {
            this.welContentInfo = welContentInfo;
            this.isWelContentShow = true;
        },
        onPreviewClose() {
            this.welContentInfo = {};
            this.isWelContentShow = false;
        },
        handleSizeChange(pageSize) {
            this.page.pageSize = pageSize;
            this.page.currentPage = 1;
            this.getChannelCodeList();
        },
        handleCurrentChange(currentPage) {
            this.page.currentPage = currentPage;
            this.getChannelCodeList();
        },
        changeStatisticsDetailShow(type) {
            this.isStatisticsCstDetailShow = type;
        }
    },
    beforeDestroy() {
        document.removeEventListener('click', this.closeInput);
    }
};
</script>

<style lang="scss" scoped>
.madp-livecode {
    &-component {
        padding-top: 40px;
    }
    /deep/ .madp-livecode-search-form {
        display: flex;
        flex-direction: row;
        justify-content: flex-end;
    }
    &-container {
        margin-top: 20px;
        display: flex;
        &-left {
            width: 220px;
            min-height: 63vh;
            box-sizing: border-box;
            border: 1px solid #e6e6e6;
            margin-right: 10px;
            &-add {
                .group-name-add {
                    line-height: 50px;
                    display: flex;
                    align-items: center;
                    border-bottom: 1px solid #e6e6e6;
                    cursor: pointer;
                    .el-icon-circle-plus {
                        padding: 0 10px 0 24px;
                        color: #1890ff;
                    }
                }
                .group-name-input {
                    padding: 16px 19px 16px 24px;
                }
            }
            .group-name-list {
                &-item {
                    padding-left: 24px;
                    line-height: 40px;
                    display: flex;
                    justify-content: space-between;
                    cursor: pointer;
                    &:last-child {
                        border: none;
                    }
                    &.actived,
                    &.selected {
                        background-color: #effaff;
                        color: rgba(0, 0, 0, 0.65);
                    }
                    &.selected {
                        border-left: 3px solid #1890ff;
                        padding-left: 21px;
                    }
                    &-name,
                    &-info {
                        display: flex;
                        align-items: center;
                    }
                    &-name {
                        .name-text {
                            width: 120px;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }
                        img {
                            width: 18px;
                            height: 18px;
                            margin-right: 3px;
                        }
                    }
                    &-info {
                        color: rgba($color: #000000, $alpha: 0.25);
                        .group-name-handle {
                            position: relative;
                            &-box {
                                display: none;
                                width: 80px;
                                .handle-common {
                                    color: #333;
                                    text-align: center;
                                    line-height: 40px;
                                    &:first-child {
                                        border-bottom: 1px solid #e6e6e6;
                                    }
                                }
                                .del-disable {
                                    color: #999999;
                                }
                            }
                            &:hover .group-name-handle-box {
                                display: block;
                                background-color: #ffffff;
                                border: 1px solid #e6e6e6;
                                position: absolute;
                                top: -20px;
                                left: 10px;
                                z-index: 999;
                            }
                            .el-icon-more {
                                transform: rotate(90deg);
                            }
                        }
                        .not-active {
                            width: 14px;
                        }
                    }
                }
            }
        }
        &-right {
            width: calc(100% - 230px);
        }
    }
}
.table-check-img {
    display: flex;
    justify-content: center;
    align-items: center;
    img {
        width: 40x;
        height: 50px;
        margin-left: 5px;
    }
}
.madp-edit-group {
    line-height: 36px;
}
.madp-code-detail {
    display: flex;
    &-left {
        width: 216px;
        padding-top: 15px;
        display: flex;
        flex-direction: column;
        align-items: center;
        img {
            width: 133px;
            height: 133px;
        }
        &-name {
            margin: 16px 0 6px 0;
        }
        &-btn {
            display: flex;
            flex-direction: column;
            .el-button {
                width: 140px;
                margin: 10px 0 0 0;
                align-items: center;
            }
        }
    }
    &-right {
        width: calc(100% - 216px);
        max-height: 60vh;
        padding: 13px 35px 0;
        border-left: 1px solid #e8e8e8;
        box-sizing: border-box;
        // overflow: auto;
        /deep/ .el-scrollbar {
            height: 100%;
            .el-scrollbar__wrap {
                overflow: auto;
                padding-right: 10px;
            }
        }
    }
}
.madp-common-title {
    line-height: 20px;
    font-weight: bold;
    border-left: 3px solid #1890ff;
    padding-left: 4px;
}
.madp-common-item {
    margin-top: 10px;
    display: flex;
    padding-left: 7px;
    &-left {
        min-width: 70px;
    }
}
.madp-wel-title {
    margin: 10px 0;
}
.madp-wel-content {
    margin-top: 10px;
    padding: 16px;
    border: 1px solid #eee;
    border-radius: 2px;
    background-color: #fbfbfb;
    &-time {
        display: flex;
        margin-bottom: 10px;
        &-left {
            white-space: nowrap;
        }
    }
    &-message {
        &-all {
            color: #1890ff;
            cursor: pointer;
        }
    }
}
.madp-wel-preview {
    position: fixed;
    top: 0;
    left: 0;
    z-index: 9999;
    width: 100%;
    height: 100%;
    background-color: rgba($color: #000000, $alpha: 0.75);
    &-box {
        height: 535px;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        img {
            height: 100%;
        }
        &-inner {
            position: absolute;
            top: 90px;
            left: 25px;
            height: 345px;
            overflow: auto;
            &::-webkit-scrollbar {
                display: none;
            }
            .madp-message {
                display: flex;
                &-left {
                    height: 26px;
                    padding: 0 6px;
                    margin-top: 5px;
                    margin-right: 10px;
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    background-color: #1890ff;
                    color: #fff;
                }
                &-common {
                    width: 180px;
                }
                &-common-box {
                    background-color: #fff;
                    padding: 5px;
                    border-radius: 5px;
                }
                &-right {
                    line-height: 18px;
                    word-break: break-all;
                    word-wrap: break-word;
                }
                &-pic {
                    img {
                        width: 100%;
                        height: auto;
                    }
                }
                &-picTxt {
                    display: flex;
                    img {
                        width: 40px;
                        height: 40px;
                    }
                    &-info {
                        font-size: 12px;
                        &-top,
                        &-bottom {
                            width: 120px;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }
                        &-bottom {
                            color: rgba($color: #000000, $alpha: 0.45);
                        }
                    }
                }
                &-applets {
                    img {
                        width: 170px;
                        height: auto;
                    }
                    &-title {
                        display: flex;
                        align-items: center;
                        img {
                            width: 20px;
                            height: 20px;
                        }
                    }
                }
            }
        }
        &-close {
            position: absolute;
            top: -10px;
            right: -40px;
            font-size: 36px;
            color: #fff;
            cursor: pointer;
        }
    }
}
.el-dropdown {
    margin-left: 10px;
}
.el-tag {
    margin-right: 5px;
    margin-bottom: 5px;
}
.madp-mt {
    margin-top: 10px;
}
.madp-change-group {
    display: flex;
    align-items: center;
    &-label {
        margin-right: 10px;
    }
    /deep/ .el-input {
        width: 400px;
        input {
            cursor: pointer;
        }
    }
    &-content {
        &-add {
            .group-name-add {
                line-height: 50px;
                display: flex;
                align-items: center;
                border-bottom: 1px solid #e6e6e6;
                cursor: pointer;
                .el-icon-circle-plus {
                    padding: 0 10px 0 24px;
                    color: #1890ff;
                }
            }
            .group-name-input {
                padding: 16px 19px 16px 24px;
            }
        }
        .group-name-list {
            &-item {
                padding: 0 24px;
                line-height: 40px;
                display: flex;
                justify-content: space-between;
                cursor: pointer;
                &:last-child {
                    border: none;
                }
                &.actived,
                &.selected {
                    background-color: #effaff;
                    color: rgba(0, 0, 0, 0.65);
                }
                &.selected {
                    border-left: 3px solid #1890ff;
                    padding-left: 21px;
                }
                &-name {
                    // width: 120px;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }
                &-info {
                    color: rgba($color: #000000, $alpha: 0.25);
                }
            }
        }
    }
}
.madp-color-tooltips {
    display: flex;
    align-items: center;
    font-size: 12px;
    &-dot {
        display: inline-block;
        width: 12px;
        height: 12px;
        border-radius: 50%;
    }
    .madp-ml {
        margin-left: 5px;
    }
}
.madp-cursor {
    cursor: url('/img/magnifier.png'), auto;
}
.page-content {
    width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
}
/deep/ .el-tooltip__popper {
    max-width: 50%;
}
</style>
